<?php

	// +----------------------------------------------------------------------
	// | 二维码处理
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\event\file;

	use think\Exception;
	use think\facade\Config;
	use think\facade\Url;
	use app\common\event\Base;
	use app\model\file\Image as ImageModel;
	use think\facade\Env;
	use yicmf\tools\HttpService;

	class QrCode extends Base
	{
		/**
		 * @param ImageModel $image
		 * @return string
		 */
		public static function read($image)
		{
			try {
				if (!Config::get('file.qr_read_driver_online')) {
					throw new Exception('咋不支持');
				}
				$res = HttpService::post('https://cli.im/apis/up/deqrimg', "img=" . urlencode($image['url']));
				$obj = json_decode($res);
				$text = $obj->info->data[0];
				if ($text == null || $text == "") {
					throw new Exception('远程识别失败');
				}
				$data['data'] = $text; //返回识别后的文本
				$data['code'] = 0;
			} catch (Exception $e) {
				try {
					$qrcode = new \Zxing\QrReader($image['path']);  //图片路径
					if (!$qrcode->text()) {
						throw new Exception('失败失败');
					}
					$data['data'] = $qrcode->text(); //返回识别后的文本
					$data['code'] = 0;
				} catch (Exception $e) {
					$data['message'] = '二维码识别出错，请在其他网站（草料二维码识别）识别二维码内容后，将内容重新生成成二维码图片上传'; //返回识别后的文本
					$data['error'] = $e->getMessage(); //返回识别后的文本
					$data['code'] = 1;
				}
			}
			return $data;
		}


		public static function build($value, $filename = null, $path = 'default', $level = 'L', $size = 5)
		{
			include_once app()->getRootPath() . 'extend/phpqrcode.php';
			if (is_null($filename)) {
				$filename = uniqid() . '.png';
			}
			$dir = app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'qrcode' . DIRECTORY_SEPARATOR . $path;

			if (!is_dir($dir)) {
				//第三个参数是“true”表示能创建多级目录，iconv防止中文目录乱码
				mkdir(iconv("UTF-8", "GBK", $dir), 0777, true);
			}
			//生成二维码图片
			\QRcode::png($value, $dir . DIRECTORY_SEPARATOR . $filename, $level, $size, 2);
			return '/uploads/qrcode/' . $path . '/' . $filename;
		}

	}
